class Folder < ActiveRecord::Base
  has_many(:folder_content, :dependent => :destroy)
  has_many(:page, :through => :folder_content, :order => 'title', :dependent => :destroy)
  has_many(:function, :through => :folder_content, :dependent => :destroy)
  has_many(:sub_folder, :class_name => "Folder", :foreign_key => "sub_folder_id", :through => :folder_content, :order => "seq", :dependent => :destroy)

  has_and_belongs_to_many(:editor_group)
  has_and_belongs_to_many(:user_group)

  validates_presence_of :name
  validates_length_of :name, :maximum => 40, :allow_nil => false


  before_destroy(:remove_dependencies)
  #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  #class methods
  #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  
  class << self
    def list_for_selection(id = nil)
      rvalue = [] 
      exclude_folder = ""
      exclude_folder = "and id != #{id}" unless id.nil?
      folders = find(:all, :conditions => "(top_level is false or top_level is null) #{exclude_folder}", :order => "name")
      folders.each do |fldr|
        rvalue << {:id => fldr.id, :name => fldr.qualified_name}
      end
      rvalue.sort{|x,y| x[:name] <=> y[:name]}
    end
  end # end class block

  #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  #instance methods
  #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  
  def qualified_name
    rvalue = parent_names
    return rvalue if rvalue.length > 0
    self.name
  end

  def assign_page_to_groups(new_page)
    editor_group.each do |eg|
      eg.page << new_page unless eg.has_page_id?(new_page.id)
    end

    user_group.each do |ug|
      ug.page << new_page unless ug.has_page_id?(new_page.id)
    end
  end

  def assign_document_category_to_groups(new_dc)
    editor_group.each do |eg|
      eg.document_category << new_dc unless eg.has_document_category_id?(new_dc.id)
    end

    user_group.each do |ug|
      ug.document_category << new_dc unless ug.has_document_category_id?(new_dc.id)
    end
  end

  private
    def parent_names
      tl = Folder.find(:first, :conditions => "top_level is true")
      parent = FolderContent.find_by_sql("select * from folder_contents where folder_id != #{tl.id} and sub_folder_id = #{self.id}")
      return parent[0].folder.parent_names + " - " + self.name if parent.length > 0
      return self.name
    end

    def remove_dependencies
      FolderContent.delete_all("sub_folder_id = #{self.id}")
    end
end
